var select = '<select  ' +
    'ng-model="current_col"' +
    'ng-change="add()"' +
    'ng-options="col as col.name for col in cols_copy">' +
    '</select>';

//<div class="input-group">
//    <span class="input-group-addon">品牌</span>
//    <input type="text" class="form-control" ng-model="new_model.brand" />
//    </div>


var cols = '<div style="float:left" class="input-group col-md-2" ng-repeat = "f in filters">' +
    '<label class="input-group-addon" ng-bind="f.name">品牌</label>' +
    '<input style="padding-right: 30px;" type="text" class="form-control" ng-model="filter[f.id]">' +
    '<i class="fa fa-times" style="" ng-click="f.remove()"></i>' +
    '</div>';

var option_nil = {
    name: '过滤规则',
    id  : undefined
};

module.exports = function () {
    return {
        restrict  : 'E',
        scope     : {
            filter: "=",
            cols  : "="
        },
        template  : '<div class="filter">' + select + cols + '</div>',
        replace   : true,
        controller: ['$scope', '$element', function ($scope, $element) {

            $scope.cols_copy = $scope.cols.map(function (_) {
                return _
            });
            $scope.cols_copy.unshift(option_nil);

            $scope.filters = [];
            $scope.current_col = option_nil;

            $scope.add = function () {
                var col = $scope.current_col;
                if (!col.id) return;
                if (-1 !== $scope.filters.findIndex(function (x) {
                        return x.id == col.id
                    }))return;

                $scope.filters.push({
                    id    : col.id,
                    name  : col.name,
                    value : null,
                    remove: function () {
                        var to_remove = $scope.filters.indexOf(this);

                        $scope.filters.splice(to_remove, 1);
                        delete  $scope.filter[this.id];
                        $scope.cols_copy.push(col);
                    }
                });
                $scope.cols_copy.splice($scope.cols_copy.indexOf(col), 1);
                //flat_filters();
                $scope.current_col = option_nil
            };

        }]
    }
};